package com.cmcc.linlaker.fragment;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cmcc.linlaker.MainActivity;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.ui.query.adapter.QueryPageAdapter;
import com.cmcc.linlaker.ui.query.fragment.FarmerFragment;
import com.cmcc.linlaker.ui.query.fragment.ProjectFragment;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.zyyoona7.wheel.WheelView;

import java.util.ArrayList;
import java.util.List;

import static android.util.TypedValue.COMPLEX_UNIT_SP;

public class QueryFragment extends Fragment implements View.OnClickListener {
    private View fragmentView;

    public QueryFragment() {

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_query, container, false);

//        ((MainActivity) getActivity()).setAlpha();
        initView();

        return fragmentView;
    }

    private LinearLayout layout_search_house;
    private EditText edit_house_name;
    private LinearLayout layout_is_control, layout_nature, layout_form;
    private TextView text_is_contro, text_nature, text_form;
    private TextView text_house_cancel, text_house_search;
    private View view_house_hide;


    private View view_hide;
    private LinearLayout layout_high_search;
    private EditText edit_search;
    private RelativeLayout layout_clear;
    private LinearLayout layout_search;

    private TabLayout indicator;
    private ViewPager mViewPager;
    private QueryPageAdapter pagerAdapter;

    private EditText edit_project_name, edit_project_code, edit_things;

    private LinearLayout layout_area;
    private TextView text_area;

    private LinearLayout layout_property;
    private TextView text_property;

    private LinearLayout layout_trade;
    private TextView text_trade;

    private LinearLayout layout_approve;
    private TextView text_approve;

    private TextView text_cancel;
    private TextView text_search;

    private List<View> editList = new ArrayList<>();

    private void initView() {
        view_hide = fragmentView.findViewById(R.id.view_hide);
        view_hide.setOnClickListener(this);
        edit_project_name = fragmentView.findViewById(R.id.edit_project_name);
        edit_project_code = fragmentView.findViewById(R.id.edit_project_code);
        edit_things = fragmentView.findViewById(R.id.edit_things);
        layout_area = fragmentView.findViewById(R.id.layout_area);
        text_area = fragmentView.findViewById(R.id.text_area);
        layout_property = fragmentView.findViewById(R.id.layout_property);
        text_property = fragmentView.findViewById(R.id.text_property);
        layout_trade = fragmentView.findViewById(R.id.layout_trade);
        text_trade = fragmentView.findViewById(R.id.text_trade);
        layout_approve = fragmentView.findViewById(R.id.layout_approve);
        text_approve = fragmentView.findViewById(R.id.text_approve);
        text_cancel = fragmentView.findViewById(R.id.text_cancel);
        text_search = fragmentView.findViewById(R.id.text_search);

        layout_area.setOnClickListener(this);
        layout_property.setOnClickListener(this);
        layout_trade.setOnClickListener(this);
        layout_approve.setOnClickListener(this);
        text_cancel.setOnClickListener(this);
        text_search.setOnClickListener(this);

        layout_search = fragmentView.findViewById(R.id.layout_search);
        layout_search.setOnClickListener(this);
        layout_high_search = fragmentView.findViewById(R.id.layout_high_search);
        layout_high_search.setOnClickListener(this);

        layout_search_house = fragmentView.findViewById(R.id.layout_search_house);
        edit_house_name = fragmentView.findViewById(R.id.edit_house_name);
        layout_is_control = fragmentView.findViewById(R.id.layout_is_control);
        layout_nature = fragmentView.findViewById(R.id.layout_nature);
        layout_form = fragmentView.findViewById(R.id.layout_form);
        text_is_contro = fragmentView.findViewById(R.id.text_is_contro);
        text_nature = fragmentView.findViewById(R.id.text_nature);
        text_form = fragmentView.findViewById(R.id.text_form);
        text_house_cancel = fragmentView.findViewById(R.id.text_house_cancel);
        text_house_search = fragmentView.findViewById(R.id.text_house_search);
        view_house_hide = fragmentView.findViewById(R.id.view_house_hide);
        layout_is_control.setOnClickListener(this);
        layout_nature.setOnClickListener(this);
        layout_form.setOnClickListener(this);
        layout_search_house.setOnClickListener(this);
        text_house_cancel.setOnClickListener(this);
        text_house_search.setOnClickListener(this);
        view_house_hide.setOnClickListener(this);

        edit_search = fragmentView.findViewById(R.id.edit_search);
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    Utils.hideSoftKeyboard(getActivity(), edit_search);
                    String keyName = edit_search.getText().toString();

                    if (indicator.getSelectedTabPosition() == 0) {
                        ((ProjectFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(keyName, "", "", "", "", "", "", false);
                    } else {
                        ((FarmerFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(keyName, "", "", "", "", "", "");
//                        ((FarmerFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(keyName, "", "", "");
                    }
                    return true;
                }
                return false;
            }
        });
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyName = edit_search.getText().toString();
                if (TextUtils.isEmpty(keyName)) {
                    if (indicator.getSelectedTabPosition() == 0) {
                        reset();
                    } else {
                        resetHouse();
                    }
                }
            }
        });
        editList.add(edit_project_code);
        editList.add(edit_project_name);
        editList.add(edit_search);
        editList.add(edit_things);
        editList.add(edit_house_name);

        layout_clear = fragmentView.findViewById(R.id.layout_clear);
        layout_clear.setOnClickListener(this);

        initPagerAdapter();

        mViewPager = fragmentView.findViewById(R.id.view_pager);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(pagerAdapter);

        indicator = fragmentView.findViewById(R.id.indicator);
        indicator.setTabMode(TabLayout.MODE_FIXED);
        indicator.setupWithViewPager(mViewPager);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (i == 0) {
                    edit_search.setHint("请输入项目名称");
                } else {
                    edit_search.setHint("请输入项目名称");
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private String[] titles = {"投资项目", "其他项目"};
    private List<Fragment> fragmentList;

    /**
     * 初始化pagerAdpter
     */
    private void initPagerAdapter() {
        fragmentList = new ArrayList<>();
        fragmentList.add(ProjectFragment.newInstance());
        fragmentList.add(FarmerFragment.newInstance());

        pagerAdapter = new QueryPageAdapter(getActivity().getSupportFragmentManager(), titles, fragmentList);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_hide:
                highSearch();
                break;
            case R.id.layout_search:
                break;
            case R.id.layout_high_search:
//                if (indicator.getSelectedTabPosition() == 0) {
                highSearch();
//                } else {
//                    highHouseSearch();
//                }
                break;
            case R.id.layout_clear:
                clearEdit();
                break;
            case R.id.layout_area:
                selectRegion(text_area);
                break;
            case R.id.layout_property:
                selectUsingAttributes(text_property);
                break;
            case R.id.layout_trade:
                selectIndustry(text_trade);
                break;
            case R.id.layout_approve:
                selectApprove(text_approve);
                break;
            case R.id.text_cancel:
                layout_search.setVisibility(View.GONE);
                isSearchVisible = false;

                reset();
                break;
            case R.id.text_search:
                layout_search.setVisibility(View.GONE);
                isSearchVisible = false;
                Utils.hideSoftKeyboard(getActivity(), editList);
                search();
                break;
            case R.id.view_house_hide:
                highHouseSearch();
                break;
            case R.id.layout_search_house:
                break;
            case R.id.layout_is_control:
                selectIsControl(text_is_contro);
                break;
            case R.id.layout_nature:
                selectNature(text_nature);
                break;
            case R.id.layout_form:
                selectForm(text_form);
                break;
            case R.id.text_house_cancel:
                layout_search_house.setVisibility(View.GONE);
                isHouseSearchVisible = false;

                resetHouse();
                break;
            case R.id.text_house_search:
                layout_search_house.setVisibility(View.GONE);
                isHouseSearchVisible = false;
                Utils.hideSoftKeyboard(getActivity(), editList);
                searchHouse();
                break;
        }
    }

    /**
     * 重置农民建房
     */
    private void resetHouse() {
        Utils.hideSoftKeyboard(getActivity(), editList);

        edit_house_name.setText("");
        text_is_contro.setText("");
        text_nature.setText("");
        text_form.setText("");

        if (indicator.getSelectedTabPosition() == 1) {
//            ((FarmerFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList("", "", "", "");
        }
    }

    /**
     * 搜索农民建房
     */
    private void searchHouse() {
        String houseName = edit_house_name.getText().toString();

        String isControlValue = LinhuApp.isList.get(isControlPos).dictValue;
        String natureValue = LinhuApp.natureList.get(naturePos).dictValue;
        String formValue = LinhuApp.formList.get(formPos).dictValue;

        if (indicator.getSelectedTabPosition() == 1) {
//            ((FarmerFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(houseName, isControlValue, natureValue, formValue);
        }
    }


    /**
     * 重置
     */
    private void reset() {
        Utils.hideSoftKeyboard(getActivity(), editList);

        regionPos = -1;
        industryPos = -1;
        usingAttributesPos = -1;
        departmentPos = -1;

        edit_project_name.setText("");
        edit_project_code.setText("");

        edit_things.setText("");
        text_approve.setText("");
        text_area.setText("");
        text_property.setText("");
        text_trade.setText("");

        if (indicator.getSelectedTabPosition() == 0) {
            ((ProjectFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList("", "", "", "", "", "", "",false);
        }
    }

    /**
     * 搜索
     */
    private void search() {
        String projectName = edit_project_name.getText().toString();
        String projectCode = edit_project_code.getText().toString();
        String things = edit_things.getText().toString();
        String regionValue, industryValue, usingAttributesValue, departmentValue;

        if (regionPos == -1) {
            regionValue = "";
        } else {
            regionValue = LinhuApp.regionList.get(regionPos).id;
        }

        if (industryPos == -1) {
            industryValue = "";
        } else {
            industryValue = LinhuApp.industryList.get(industryPos).dictValue;
        }

        if (usingAttributesPos == -1) {
            usingAttributesValue = "";
        } else {
            usingAttributesValue = LinhuApp.usingAttributesList.get(usingAttributesPos).dictValue;
        }

        if (departmentPos == -1) {
            departmentValue = "";
        } else {
            departmentValue = LinhuApp.departmentList.get(departmentPos).deptId;
        }

        if (indicator.getSelectedTabPosition() == 0) {
            ((ProjectFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue, false);
        } else {
            ((FarmerFragment) fragmentList.get(indicator.getSelectedTabPosition())).getProjectSearchList(projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue);
        }
    }

    /**
     * 选择是否管控
     */
    public void selectIsControl(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "isControl", textView);
    }

    /**
     * 选择建设性质
     */
    public void selectNature(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "nature", textView);
    }

    /**
     * 选择建设形式
     */
    public void selectForm(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "form", textView);
    }

    /**
     * 选择所属地区
     */
    public void selectRegion(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "region", textView);
    }

    /**
     * 选择所属行业
     */
    public void selectIndustry(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "industry", textView);
    }

    /**
     * 选择使用属性
     */
    public void selectUsingAttributes(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "using_attributes", textView);
    }

    /**
     * 审批部门
     */
    public void selectApprove(TextView textView) {
        showDict(fragmentView.findViewById(R.id.layout_query), "department", textView);
    }

    /**
     * 清空搜索框
     */
    private void clearEdit() {
        edit_search.setText("");
    }


    private boolean isHouseSearchVisible = false;

    /**
     * 高级搜索农民建房
     */
    private void highHouseSearch() {
        Utils.hideSoftKeyboard(getActivity(), editList);

        if (isHouseSearchVisible) {
            layout_search_house.setVisibility(View.GONE);
        } else {
            layout_search_house.setVisibility(View.VISIBLE);
        }

        isHouseSearchVisible = !isHouseSearchVisible;
    }


    private boolean isSearchVisible = false;

    /**
     * 高级搜索
     */
    private void highSearch() {
        Utils.hideSoftKeyboard(getActivity(), editList);

        if (isSearchVisible) {
            layout_search.setVisibility(View.GONE);
        } else {
            layout_search.setVisibility(View.VISIBLE);
        }

        isSearchVisible = !isSearchVisible;
    }

    /**
     * 筛选条件选择
     */
    private PopupWindow popupWindow;

    public void showHighSearch(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }

        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_high_query, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow2);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAsDropDown(view);
        //添加按键事件监听
        setButtonListeners(layout);

    }

    private void setButtonListeners(RelativeLayout layout) {
        EditText edit_project_name = layout.findViewById(R.id.edit_project_name);
        EditText edit_project_code = layout.findViewById(R.id.edit_project_code);
        EditText edit_things = layout.findViewById(R.id.edit_things);

        LinearLayout layout_area = layout.findViewById(R.id.layout_area);
        final TextView text_area = layout.findViewById(R.id.text_area);

        LinearLayout layout_property = layout.findViewById(R.id.layout_property);
        final TextView text_property = layout.findViewById(R.id.text_property);

        LinearLayout layout_trade = layout.findViewById(R.id.layout_trade);
        final TextView text_trade = layout.findViewById(R.id.text_trade);

        LinearLayout layout_approve = layout.findViewById(R.id.layout_approve);
        final TextView text_approve = layout.findViewById(R.id.text_approve);

        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

        TextView text_search = layout.findViewById(R.id.text_search);
        text_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

        layout_area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectRegion(text_area);
            }
        });

        layout_property.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectUsingAttributes(text_property);
            }
        });

        layout_trade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectIndustry(text_trade);
            }
        });

        layout_approve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectApprove(text_approve);
            }
        });
    }

    private int regionPos = -1;
    private int industryPos = -1;
    private int usingAttributesPos = -1;
    private int departmentPos = -1;

    private int isControlPos;
    private int naturePos;
    private int formPos;

    private PopupWindow popupSelectWindow;

    private void showDict(View view, final String tag, final TextView textView) {
        if (popupSelectWindow != null && popupSelectWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_dict, null);
        popupSelectWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);


        //点击空白处时，隐藏掉pop窗口
        popupSelectWindow.setFocusable(true);
        popupSelectWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupSelectWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupSelectWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout, tag, textView);
    }

    private void setButtonListeners(RelativeLayout layout, final String tag, final TextView textView) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final WheelView wheelview = layout.findViewById(R.id.wheelview);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupSelectWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupSelectWindow.dismiss();
                if (tag.equals("using_attributes")) {
                    usingAttributesPos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.usingAttributesList.get(usingAttributesPos).dictLabel);
                } else if (tag.equals("industry")) {
                    industryPos = wheelview.getSelectedItemPosition();

                    String industryStr = LinhuApp.industryList.get(industryPos).dictLabel;
                    textView.setText(industryStr);
                    if (industryStr.length() <= 4) {
                        textView.setTextSize(COMPLEX_UNIT_SP, 12);
                    } else {
                        textView.setTextSize(COMPLEX_UNIT_SP, 9);
                    }
                } else if (tag.equals("region")) {
                    regionPos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.regionList.get(regionPos).name);
                } else if (tag.equals("department")) {
                    departmentPos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.departmentList.get(departmentPos).deptName);
                } else if (tag.equals("isControl")) {
                    isControlPos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.isList.get(isControlPos).dictLabel);
                } else if (tag.equals("nature")) {
                    naturePos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.natureList.get(naturePos).dictLabel);
                } else if (tag.equals("form")) {
                    formPos = wheelview.getSelectedItemPosition();
                    textView.setText(LinhuApp.formList.get(formPos).dictLabel);
                }

            }
        });

        //设置数据
        if (tag.equals("region")) {
            wheelview.setData(LinhuApp.regionList);
        } else if (tag.equals("industry")) {
            wheelview.setData(LinhuApp.industryList);
        } else if (tag.equals("using_attributes")) {
            wheelview.setData(LinhuApp.usingAttributesList);
        } else if (tag.equals("department")) {
            wheelview.setData(LinhuApp.departmentList);
        } else if (tag.equals("isControl")) {
            wheelview.setData(LinhuApp.isList);
        } else if (tag.equals("nature")) {
            wheelview.setData(LinhuApp.natureList);
        } else if (tag.equals("form")) {
            wheelview.setData(LinhuApp.formList);
        }
        //尽请使用各种方法
        wheelview.setTextSize(20f, true);
        wheelview.setNormalItemTextColor(0xff666666);
        wheelview.setSelectedItemTextColor(0xff000000);
        wheelview.setDividerPaddingForWrap(13f);

        if (tag.equals("using_attributes")) {
            wheelview.setSelectedItemPosition(usingAttributesPos);
        } else if (tag.equals("industry")) {
            wheelview.setSelectedItemPosition(industryPos);
        } else if (tag.equals("region")) {
            wheelview.setSelectedItemPosition(regionPos);
        } else if (tag.equals("department")) {
            wheelview.setSelectedItemPosition(departmentPos);
        } else if (tag.equals("isControl")) {
            wheelview.setSelectedItemPosition(isControlPos);
        } else if (tag.equals("nature")) {
            wheelview.setSelectedItemPosition(naturePos);
        } else if (tag.equals("form")) {
            wheelview.setSelectedItemPosition(formPos);
        }
    }

}
